﻿using System.Net.WebSockets;
using System.Text;

namespace WebAPI.WS;

public class WebSocketClient
{
    static async Task Main(string[] args)
    {
        var client = new ClientWebSocket();
        await client.ConnectAsync(new Uri("ws://localhost:5000/ws"), CancellationToken.None);
        var message = "Hello, WebSocket!";
        var buffer = Encoding.UTF8.GetBytes(message);
        var segment = new ArraySegment<byte>(buffer);
        await client.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
        var receiveBuffer = new byte[1024];
        var result = await client.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
        Console.WriteLine(Encoding.UTF8.GetString(receiveBuffer, 0, result.Count)); // 输出接收到的消息
        await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
    }
}